package com.sddnytsh.body_buildingsystem.components

import android.util.Log
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import com.sddnytsh.body_buildingsystem.R

/**
 * 优化的头像图片组件
 * 使用AsyncImage提高加载性能，支持缓存
 */
@Composable
fun SimpleAvatarImage(
    avatarUrl: String,
    fallbackName: String,
    size: Dp = 48.dp,
    modifier: Modifier = Modifier
) {
    val context = LocalContext.current

    // 构建完整的URL
    val fullUrl = if (avatarUrl.startsWith("http")) {
        avatarUrl
    } else {
        // 🔥 修复：使用正确的服务器地址而不是localhost
        "https://expiratory-uncontortedly-alyson.ngrok-free.app$avatarUrl"
    }

    Log.d("SimpleAvatarImage", "显示头像: $fullUrl")

    AsyncImage(
        model = fullUrl,
        contentDescription = "用户头像",
        modifier = modifier
            .size(size)
            .clip(CircleShape),
        contentScale = ContentScale.Crop,
        error = painterResource(id = R.drawable.person),
        placeholder = painterResource(id = R.drawable.person),
        // 🔥 优化：添加图片加载配置，减少解码警告
        onError = { 
            Log.w("SimpleAvatarImage", "头像加载失败: $fullUrl")
        },
        onSuccess = {
            Log.d("SimpleAvatarImage", "头像加载成功: $fullUrl")
        }
    )
}